function startTree(x1,y1,x2,y2)
	local start = createWayPoint(x1,y1)
	table.insert(currentPoints,start)
	table.insert(finalPath, start)
end

function runPath(x2,y2)
	for i,v in ipairs(currentPoints) do
		createBranch(v,v.x,v.y,v.angle,x2,y2,v.ttl, 20)
	end
end

function cleanPath(distance, endX, endY)
	local continue = #moonsPath
	local current = moonsPath[1]
	while continue > 0 do 
		table.insert(finalPath, current)
		local previous = current
		local start = false
		for i,v in ipairs(moonsPath) do
			if getDistance(v.x, v.y, endX, endY) < distance then
				continue = 1
				table.insert(finalPath, v)
				break
			end
			if v.x == current.x and v.y == current.y then
				start = true
			end 
			if start then
				if not goodLine(current.x, current.y, v.x, v.y, 15) then
					table.insert(finalPath, previous)
					break
				end
				previous = v
			end
		end
		current = previous
		continue = continue - 1
	end
	table.insert(finalPath, createWayPoint(endX, endY))
	for i,v in ipairs(finalPath) do
		if finalPath[i+1] ~= nil then
			finalDist = finalDist + getDistance(v.x, v.y, finalPath[i+1].x, finalPath[i+1].y)
		end
	end
	return 0
end

function createBranch(self,x1,y1,angle,x2,y2,ttl, moveDist)
	if #successfulPoints > 0 then
		if pathFound == false then
			for i,v in ipairs(waypoints) do
				if v.successfulPath then
					table.insert(moonsPath, v)
				end
			end
			for i,v in ipairs(moonsPath) do
				if moonsPath[i+1] ~= nil then
					moonsDist = moonsDist + getDistance(v.x, v.y, moonsPath[i+1].x, moonsPath[i+1].y)
				end
			end
			cleanPath(moveDist-1, moonsPath[#moonsPath].x, moonsPath[#moonsPath].y) 
			pathFound = true
		end
		return
	end

	if getDistance(x1,y1,x2,y2) < 30 then
		self.successfulPath = true
		local tempNode = self
		
		while tempNode.prev ~= nil  and tempNode ~= nil do
			table.insert(successfulPoints,self)
			--self.pathLength = self.pathLength + 1
			tempNode.successfulPath = true
			
			tempNode = tempNode.prev
		end
		pathRunning = false
		return
	end

	--if dead return -1
	if ttl <= 0 then
		return
	end
	
	angle = calculateAngle(x1,y1,x2,y2)
	self.angle = angle
	
	local i = 0
	
	while math.abs(i) < 9 do
		local xx = 0
		local yy = 0

		xx,yy = move(x1,y1,angle + (i*math.pi/8), moveDist)

		local spaceFree = goodPoint(xx, yy, 15, false)
		
		if spaceFree == true then
			local child = createWayPoint(xx,yy)
			self.next = child
			table.insert(self.children,child)
			child.pathLength = self.pathLength + 1
			child.prev = self
			child.ttl = self.ttl - 1
			table.insert(currentPoints,child)		
		end
		
		if i < 0 then
			i = (i-1) * -1
		else
			i = (i + 1) * -1
		end
	end
	
	table.remove(currentPoints,self.index)
end
